package com.findviewbydream.evil.eda.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.R;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Utils
 * 时间：16-7-8 下午6:07
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：工具类 1.0.1
 ********************************************/
public class Utils
{
    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    private static Context context;
    private static boolean debug = false;
    private static String tag;
    private static Toast toast;

    /**
     * 初始化工具类,写在Application.class
     *
     * @param application
     */
    public static void initUtils(Application application)
    {
        context = application.getApplicationContext();
    }

    /**
     * 获取Context
     *
     * @return
     */
    public static Context getContext()
    {
        return context;
    }

    /**
     * 设置是后开启debug模式
     *
     * @param debug true 开启, false 关闭
     * @param tag   Tag标签信息
     */
    public static void setDebug(boolean debug, String tag)
    {
        Utils.debug = debug;
        Utils.tag = tag;
    }

    public static boolean getDubug()
    {
        return debug;
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Logger(String msg)
    {
        Logger.i(msg);
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Logger(Object msg)
    {
        Logger.i(msg.toString());
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Log(String msg)
    {
        Log.i(Utils.tag, msg);
    }

    /**
     * 日志输出,自定义tag
     *
     * @param tag
     * @param msg
     */
    public static void Log(String tag, String msg)
    {
        Log.i(tag, msg);
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Log(Object msg)
    {
        Log.i(Utils.tag, msg.toString());
    }

    /**
     * 日志输出,自定义tag
     *
     * @param tag
     * @param msg
     */
    public static void Log(String tag, Object msg)
    {
        Log.i(tag, msg.toString());
    }

    /**
     * Toast打印,短时间
     *
     * @param msg
     */
    public static void Toast(String msg)
    {
        if (toast == null)
        {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        }
        else
        {
            toast.setText(msg);
            toast.setDuration(Toast.LENGTH_SHORT);
        }

        toast.show();
    }

    /**
     * Toast打印,长时间
     *
     * @param msg
     */
    public static void ToastLong(String msg)
    {
        if (toast == null)
        {
            toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        }
        else
        {
            toast.setText(msg);
            toast.setDuration(Toast.LENGTH_LONG);
        }

        toast.show();
    }

    /**
     * Toast打印,短时间
     *
     * @param msg
     */
    public static void Toast(Object msg)
    {
        Toast.makeText(Utils.context, msg.toString(), Toast.LENGTH_SHORT).show();
    }

    /**
     * Toast打印,长时间
     *
     * @param msg
     */
    public static void ToastLong(Object msg)
    {
        Toast.makeText(Utils.context, msg.toString(), Toast.LENGTH_LONG).show();
    }

    /**
     * 线程休眠
     *
     * @param millis
     */
    public static void Threadsleep(int millis)
    {
        try
        {
            Thread.sleep(millis);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }


    /**
     * Glide图片加载
     *
     * @param url
     * @param imageView
     */
    public static void Glide(String url, ImageView imageView)
    {
        Glide.with(context)
                .load(url)
                .placeholder(R.drawable.loading2)
                .error(R.drawable.fail)
                .into(imageView);
    }

    /**
     * Glide图片加载
     *
     * @param res
     * @param imageView
     */
    public static void Glide(int res, ImageView imageView)
    {
        Glide.with(context).load(res).into(imageView);
    }


    /**
     * Glide图片加载
     *
     * @param url
     * @param imageView
     */
    public static void Glide(Context context, String url, ImageView imageView)
    {
        Glide.with(context).load(url).centerCrop().into(imageView);
    }

    /**
     * Glide图片加载
     *
     * @param res
     * @param imageView
     */
    public static void Glide(Context context, int res, ImageView imageView)
    {
        Glide.with(context).load(res).centerCrop().into(imageView);
    }


    /**
     * 获取版本名
     *
     * @return
     */
    public static String getVersionName()
    {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try
        {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return info.versionName;
    }


    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode()
    {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try
        {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return info.versionCode;
    }


    /**
     * 获取颜色
     *
     * @param res
     * @return
     */
    public static int getColor(int res)
    {
        return context.getResources().getColor(res);
    }


    /**
     * dp转px
     *
     * @param dpValue
     * @return
     */
    public static int dpTopx(float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * px转dp
     *
     * @param pxValue
     * @return
     */
    public static int pxTodp(float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 取屏幕宽度
     *
     * @return
     */
    public static int getScreenWidth()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 取屏幕高度
     *
     * @return
     */
    public static int getScreenHeight()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels - getStatusBarHeight();
    }

    /**
     * 取屏幕高度包含状态栏高度
     *
     * @return
     */
    public static int getScreenHeightWithStatusBar()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 取导航栏高度
     *
     * @return
     */
    public static int getNavigationBarHeight()
    {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0)
        {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHeight()
    {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0)
        {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 判断应用是否处于后台状态
     *
     * @return
     */
    public static boolean isBackground()
    {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty())
        {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName()))
                return true;
        }
        return false;
    }

    /**
     * 复制文本到剪贴板
     *
     * @param text
     */
    public static void copyToClipboard(String text)
    {
        if (Build.VERSION.SDK_INT >= 11)
        {
            ClipboardManager cbm = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
            cbm.setPrimaryClip(ClipData.newPlainText(context.getPackageName(), text));
        }
        else
        {
            android.text.ClipboardManager cbm = (android.text.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
            cbm.setText(text);
        }
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference()
    {
        return context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference(String name)
    {
        return context.getSharedPreferences(name, Activity.MODE_PRIVATE);
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference(String name, int mode)
    {
        return context.getSharedPreferences(name, mode);
    }

    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
     */
    public static int getNetworkType()
    {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null)
            return netType;
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE)
        {
            String extraInfo = networkInfo.getExtraInfo();
            if (!extraInfo.equals("") && extraInfo != null)
            {
                if (extraInfo.toLowerCase().equals("cmnet"))
                    netType = NETTYPE_CMNET;
                else
                    netType = NETTYPE_CMWAP;
            }
        }
        else if (nType == ConnectivityManager.TYPE_WIFI)
            netType = NETTYPE_WIFI;
        return netType;
    }


    /**
     * 线程操作与UI更新
     */
    public static abstract class SHandler
    {
        public abstract void handler();

        public void thread()
        {
        }

        public void thread(Handler handler)
        {
        }

        public void startByCustom()
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    thread(handler);
                }
            });
            thread.start();
        }

        public void start()
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    thread();
                    handler.sendEmptyMessage(0);
                }
            });
            thread.start();
        }

        public void start(final int sleepTime)
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        Thread.sleep(sleepTime);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    thread();
                    handler.sendEmptyMessage(0);
                }
            });
            thread.start();
        }
    }

    /**
     * EventBus事件发送
     *
     * @param o
     */
    public static void EventBusPost(Object o)
    {
        EventBus.getDefault().post(o);
    }


    /**
     * 获取手机IMEI,android 6.0以上需要获取权限
     *
     * @return
     */
    public static String getIMEI()
    {
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    /**
     *
     */
    public static String getNetImg(String path)
    {
        return Data.IP + "image/" + path;
    }


}
